// ignore_for_file: avoid_print

import 'dart:io';
import 'dart:convert';
import 'dart:math';

import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';

void main() {
  var ms = MockServer();
  ms.start();
}

class MockServer {
  late HttpServer _server;
  bool isRunning = false;
  String posts = '''
{
  "posts": [
    { "id": "1", "title": "a title", "views": 100 },
    { "id": "2", "title": "another title", "views": 200 }
  ],
  "comments": [
    { "id": "1", "text": "a comment about post 1", "postId": "1" },
    { "id": "2", "text": "another comment about post 1", "postId": "1" }
  ],
  "profile": {
    "name": "typicode"
  }
}
''';
  start() async {
    if (isRunning) {
      return;
    }
    var app = Router(notFoundHandler: (request) {
      print('【🚄】[not found] ${request.requestedUri} ');
      final segments = request.url.pathSegments;
      dynamic result;
      String json = posts;
      try {
        for (var e in segments) {
          result ??= jsonDecode(json);
          if (result is Map) {
            result = result[e];
          } else if (result is List) {
            result = result.elementAt(int.parse(e));
          } else {
            break;
          }
        }
      } catch (e) {
        return shelf.Response.badRequest(body: e);
      }
      return shelf.Response.ok(jsonEncode(result));
    })
      ..get('/api/admin/signin', _cookieHandler);
    _server = await shelf_io.serve(app.call, 'localhost', 3000, shared: true);
    _server.autoCompress = true;
    print('【⬆️ 】Serving at http://${_server.address.host}:${_server.port}');
    isRunning = true;
  }

  stop() async {
    if (isRunning) {
      await _server.close();
      print('【⬇️ 】Server is shutting down!');
    }
  }

  shelf.Response _cookieHandler(shelf.Request request) {
    final response =
        shelf.Response.ok(jsonEncode({'code': 200, 'msg': 'oook'}));
    response.change(headers: {
      HttpHeaders.setCookieHeader: [
        Cookie('uuid', '${Random().nextInt(1000)}'),
        Cookie('uuidv1', '${Random().nextInt(1000)}')
      ].map((ck) => ck.toString()).join(', ')
    });
    return response;
  }
}
